package com.sos.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 1. 创建 ObjectMapper 并配置 Java 8 时间类型支持
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册 JavaTimeModule，支持 LocalDateTime/LocalDate 等 Java 8 时间类型
        objectMapper.registerModule(new JavaTimeModule());
        // 关闭“将时间序列化为时间戳”的默认行为（可选，改为字符串格式，更易读）
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // 2. 配置 Redis 序列化器（使用自定义的 ObjectMapper）
        GenericJackson2JsonRedisSerializer jacksonSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
        StringRedisSerializer stringSerializer = new StringRedisSerializer();

        // 3. 设置 Key/Value 的序列化方式
        template.setKeySerializer(stringSerializer);          // Key 用字符串序列化
        template.setValueSerializer(jacksonSerializer);       // Value 用 Jackson 序列化
        template.setHashKeySerializer(stringSerializer);      // Hash Key 用字符串序列化
        template.setHashValueSerializer(jacksonSerializer);   // Hash Value 用 Jackson 序列化

        template.afterPropertiesSet();
        return template;
    }
}